package com.kate.mall.bff.wx.config;

import cn.hutool.core.util.StrUtil;
import com.kate.mall.common.constants.AuthConstant;
import com.kate.mall.log.constants.TraceConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
@Slf4j
public class FeignInterceptorConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        RequestInterceptor requestInterceptor = new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate template) {
                //#####################################传递traceId#####################################
                String traceId = StrUtil.isNotEmpty(MDC.get(TraceConstant.LOG_TRACE_ID))  ?
                        MDC.get(TraceConstant.LOG_TRACE_ID) :  MDC.get(TraceConstant.LOG_B3_TRACEID) ;
                if (StrUtil.isNotEmpty(traceId)) {
                    template.header(TraceConstant.HTTP_HEADER_TRACE_ID, traceId);
                }
                //#####################################feign 丢失请求头#####################################
                //1.RequestContextHolder拿到当前请求的数据，相当与拿到controller入参的HttpServletRequest
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes!=null){
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    if (request!=null){
                        //2.同步请求头信息->Authorization
                        String jwt = request.getHeader(AuthConstant.JWT_TOKEN_HEADER);
                        log.info("feign header jwt====>{}",jwt);
                        template.header(AuthConstant.JWT_TOKEN_HEADER, jwt);
                    }
                }

            }
        };
        return requestInterceptor;
    }
}